<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable ref="table" :isSelectColumn="false" :columns="columns" :fetchapi="fetchApi" :params="fetchParams" :datakey="'records'" :onColumnsChange="columns => (this.columns = columns)">
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="addHandle">新增</el-button>
      </template>
    </FilterTable>

    <BaseDialog :visible.sync="visible" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SMSPanel :type="handleType" :recordVersion="recordVersion" :smsTemplateId="smsTemplateId" :rowData="formData" @close="closeHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import { getSMSTemplateList, deleteSMSTemplate } from '@/api/customerRepair/visitRules/SMSTemplate2';
import { dictionary } from '@/utils/dictMixin';
import SMSPanel from './SMSPanel';

export default {
  name: 'SMSTemplate',
  components: {
    SMSPanel
  },
  mixins: [dictionary],
  data() {
    this.conf = { add: '新增', edit: '编辑' };
    return {
      topFilterList: this.createTopFilters(),
      columns: this.createTableColumns(),
      fetchApi: getSMSTemplateList,
      fetchParams: {},
      handleType: '',
      formData: {},
      dialogTitle: '',
      smsTemplateId: '',
      recordVersion: '',
      visible: false
    };
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'SELECT',
          label: '模板类型',
          fieldName: 'type',
          placeholder: '请选择...',
          itemList: this.createDictList('1572')
        },
        {
          type: 'INPUT',
          label: '模板名称',
          fieldName: 'name',
          placeholder: '请输入...'
        },
        {
          type: 'SELECT',
          label: '数据来源',
          fieldName: 'dataSource',
          placeholder: '请选择...',
          itemList: this.createDictList('1045')
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" disabled={props.row.dataSources == 10451002 ? true : false} onClick={() => this.editHandle(props.row)}>
                  编辑
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" disabled={props.row.dataSources == 10451002 ? true : false} onClick={() => this.deleteHandle(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '短信模板类型',
          dataIndex: 'smsTemplateType',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1572'),
          render: props => {
            return <span>{this.createDictText(props.row.smsTemplateType, '1572')}</span>;
          }
        },
        {
          title: '短信模板名称',
          dataIndex: 'smsTemplateName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '短信模板内容',
          dataIndex: 'smsTemplateContent',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return this.templateFormat(props.row.smsTemplateContent);
          }
        },
        {
          title: '是否默认',
          dataIndex: 'isDefault',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isDefault, '1004')}</span>;
          }
        },
        {
          title: '数据来源',
          dataIndex: 'dataSources',
          sorter: true,
          filter: true,
          filterType: 'input',
          filterItems: this.createDictList('1045'),
          render: props => {
            return <span>{this.createDictText(props.row.dataSources, '1045')}</span>;
          }
        }
      ];
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}短信模板`;
      this.visible = true;
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    editHandle(row) {
      this.handleType = 'edit';
      this.smsTemplateId = row.smsTemplateId;
      this.recordVersion = row.recordVersion;
      row.templateContent = this.templateFormat(row.smsTemplateContent);
      this.formData = row;
      this.showHandler();
    },
    templateFormat(template) {
      if (template !== '') {
        var reg = new RegExp('\\{\\[[^(\\s|\\})]+\\]\\}', 'g');
        var reg2 = new RegExp('[^\\{\\[\\]\\}]+', 'g');
        var matchResult = template.match(reg);
        if (!matchResult) {
          return template;
        }
        var matchKeys;
        for (let i = 0; i < matchResult.length; i++) {
          var result = matchResult[i].match(reg2);
          var val = this.createDictText(result, result[0].substring(0, 4));
          if (val || val == '') {
            matchKeys = matchKeys == undefined ? {} : matchKeys;
            matchKeys[result] = '{[' + val + ']}';
          }
        }
        for (var key in matchKeys) {
          var reg3 = new RegExp('(\\{\\[' + key + '\\]\\})', 'g');
          template = template.replace(reg3, matchKeys[key]);
        }
        return template;
      } else {
        return this;
      }
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    deleteHandle(row) {
      this.$confirm('此操作将删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteSMSTemplate({ smsTemplateId: row.smsTemplateId })
            .then(res => {
              if (res.resultCode == 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
                this.fetchParams = { ...this.fetchParams };
              }
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    }
  }
};
</script>

<style lang="less"></style>
